//
//  KDChildNewsController.m
//  WangJingApp
//
//  Created by 魏强 on 17/1/4.
//  Copyright © 2017年 KDTech. All rights reserved.
//

#import "KDChildNewsController.h"
/**  text model */
#import "KDGetMonitorListParam.h"
#import "KDGetKeywordListParam.h"
#import "KDMGetWebListParam.h"
#import "KDGetAuthorListParam.h"
#import "KDGetAppListParam.h"
#import "KDMBaseBoardModel.h"
#import "KDBaesMonitorModel.h"
#import "KDMonitorRequestTool.h"
#import "KDMKeywordMonitorResult.h"
#import "KDMListCell.h"
#import "KDMListCellBaseModel.h"
#import "KDMBaseBoardModel.h"

#import "GBSingleWebViewController.h"
#import "KDReportController.h"
#import "KDPatrolgetReportParam.h"
#import "KDMRelationController.h"



@interface KDChildNewsController ()<UITableViewDelegate,UITableViewDataSource, KDMListCellDelegate>
/** 当前显示的tableView*/
@property (nonatomic, weak) UITableView *currentTabV;
/**
 *  加载第几页
 */
@property (nonatomic, strong) NSString *page;
///** 当前的baseBoardModel*/
//@property (nonatomic, strong) KDMBaseBoardModel *baseBoardModel;
/** 默认的baseBoardModel*/
@property (nonatomic, strong) KDMBaseBoardModel * defaultBaseBoardModel;
/**
 * tableView的model的数据*
 */
@property (nonatomic, strong) NSDictionary *dataDic;
/**
 *  所有的列表数据
 */
@property (nonatomic, strong) NSArray *infoArr;
/**
 *  版本
 */
@property (nonatomic, assign) NSInteger version;
/**
 *  用户地区:1:区级 2:市级 3:省级 4：全国
 */
@property (nonatomic, assign) NSInteger regionType;
@end

@implementation KDChildNewsController
#pragma mark - 懒加载区
- (NSString *)page
{
    if (!_page) {
        _page = @"1";
    }
    return _page;
}
- (NSArray *)infoArr
{
    if (!_infoArr) {
        _infoArr = [NSArray new];
    }
    return _infoArr;
}
- (KDMBaseBoardModel *)baseBoardModel
{
    if (!_baseBoardModel) {//那里找不到了，就自己建
        _baseBoardModel = [[KDMBaseBoardModel alloc]init];
        _baseBoardModel.webSrcType = @"0";
        //        NSDate *newdate = [[NSDate date] initWithTimeInterval:- (24 *60 * 60 * 6 )sinceDate:[NSDate date]];
        _baseBoardModel.startTime = @"1970-01-01";//[self.fmt stringFromDate:newdate];
        _baseBoardModel.endTime = @"";
        _baseBoardModel.timeIndex = @"9";
        _baseBoardModel.docType = @"0";
        _baseBoardModel.bussiness = @"0";
        if (self.mainType == 3 || self.mainType == 1) {
            if (self.regionType == 0) {
                _baseBoardModel.regionType = 4;
            }else{
                _baseBoardModel.regionType = self.regionType;
            }
        }
        self.defaultBaseBoardModel = _baseBoardModel ;
    }
    return _baseBoardModel;
}
#pragma mark - 生命周期区
- (void)viewDidLoad {
    [super viewDidLoad];
    KDAccount *account = [KDAccountTool account];
    self.version = account.version;
    [self setUpTableView];
    // Do any additional setup after loading the view.
}
#pragma mark - 板块布置区
/***  各大主题tableView的设置*/
- (void)setUpTableView
{
    UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0  , 0, screenW, self.view.height  - 64) style:UITableViewStylePlain];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.tag = 1000;
    tableView.tableFooterView = [UIView new];
    tableView.separatorColor = BackGroundColor;
    tableView.backgroundColor = BackGroundColor;
    tableView.rowHeight = Cell_h;
    if (!iOS7) {
        tableView.estimatedRowHeight = Cell_h;
    }
    self.currentTabV = tableView;
    [self.view addSubview:tableView];
    UINib *xib =  (self.version)? [UINib nibWithNibName:@"KDMListCell2" bundle:nil] :[UINib nibWithNibName:@"KDMListCell" bundle:nil];
    [tableView registerNib:xib forCellReuseIdentifier:@"KDMListCell"];

    tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadDetailData)];
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreDetailData)];
    [footer setTitle:@"" forState:MJRefreshStateIdle];
    // 设置footer
    self.currentTabV.footer = footer;
    [self.currentTabV.header beginRefreshing];
}

#pragma mark - 事件点击区

#pragma mark - 网络请求区
- (void)beginRefresh{
    [self.currentTabV.header beginRefreshing];
}

- (KDGetMonitorListParam *)requestMethod{
    KDGetMonitorListParam *param1;
//    if (!self.themeArr.count) {//没有二级菜单，返回无数据
////        [self setUpNoMoreNotise];
//        return nil;
//    }
    //创建参数
    switch (self.mainType) {//
        case 0:{
            KDGetKeywordListParam *param = [[KDGetKeywordListParam alloc]init];
            param.method = @"getMonitorKeywordItemList";
            param.p = self.page;
            param.limit = @"20";
            param.kindType = self.baseBoardModel.webSrcType;
            param.startTime = self.baseBoardModel.startTime;
            param.endTime = self.baseBoardModel.endTime;
            param.property = self.baseBoardModel.docType;
            param.sortType = @"0";
            param.keyword = self.baseBoardModel.secondSearch;
            
//            KDBaesMonitorModel *model = self.themeArr[self.currentIndex.integerValue];
            param.m_Id =  self.model.m_Id ;
            param1 = param;
            break;
        }
        case 1:{
            
            KDMGetWebListParam *param = [[KDMGetWebListParam alloc]init];
            param.method = @"getMonitorWebSiteItemList";
            param.p = self.page;
            param.business = (self.baseBoardModel.bussiness.integerValue)?@"true":@"false";
            param.keyword = self.baseBoardModel.secondSearch;
            param.startTime = self.baseBoardModel.startTime;
            param.endTime = self.baseBoardModel.endTime;
            param.property = self.baseBoardModel.docType;//
            param.limit = @"20";
            param.pageId = self.baseBoardModel.pageId;
            param.regionType = self.baseBoardModel.regionType;
//            KDBaesMonitorModel *model = self.themeArr[self.currentIndex.integerValue];
            param.wsm_id = self.model.m_Id ;
            param1 = param;
            break;
        }
        case 2:{
            KDGetAuthorListParam *param = [[KDGetAuthorListParam alloc]init];
            param.method = @"getMonitorAuthorItemList";
            param.startTime = self.baseBoardModel.startTime;
            param.endTime = self.baseBoardModel.endTime;
            param.property = self.baseBoardModel.docType;
            param.p = self.page;
            param.limit = @"20";
            param.keyword = self.baseBoardModel.secondSearch;
            param.kindType = self.baseBoardModel.webSrcType;
            param.sortType = @"0";
//            KDBaesMonitorModel *model = self.themeArr[self.currentIndex.integerValue];
            param.a_id =  self.model.m_Id;
            param1 = param;
            break;
        }
        case 3:{
            KDGetAppListParam *param = [[KDGetAppListParam alloc]init];
            param.method = @"getMonitorAppItemList";
            param.p = self.page;
            param.limit = @"20";
            param.startTime = self.baseBoardModel.startTime;
            param.endTime = self.baseBoardModel.endTime;
            //            param.property = self.baseBoardModel.docType;
            param.business = (self.baseBoardModel.bussiness.integerValue)?@"true":@"false";//待定
            param.keyword = self.baseBoardModel.secondSearch;
            param.property = self.baseBoardModel.docType;
            param.sortType = @"0";
            param.regionType = self.baseBoardModel.regionType;
//            KDBaesMonitorModel *model = self.themeArr[self.currentIndex.integerValue];
            param.app_id = self.model.m_Id ;
            param1 = param;
            break;
        }
        default:
            break;
    }
    return param1;
}
- (void)loadDetailData{
//    if (self.notice) {
//        [self.notice removeFromSuperview];
//    }
    
    self.currentTabV.tableHeaderView.height = 0;
    self.page = @"1";
    KDGetMonitorListParam *param = [self requestMethod];
    if (!param) {//如果没有子主题了就不要再请求了
        [self.currentTabV.header endRefreshing];
        return;
    }
    WS(ws);
    [KDMonitorRequestTool getMonitorListWithParam:param WithMainType:self.mainType success:^(KDMKeywordMonitorResult * responseObejct) {
        KDMKeywordMonitorResult *result = responseObejct;
        if ([result.status isEqualToString:@"notlogin"]) {//如果被别人强制登陆了
            //写提示“该账号已在别处登录”
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"该账号已在别处登录" message:@"请重新登录" delegate:ws cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alertView show];
            [ws.currentTabV.header endRefreshing];
            
        }else{//正常情况下，就加载数据
//            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            if (!result.info) {
//                [ws setUpNoMoreNotise];
                [ws.currentTabV.header endRefreshing];
                return ;
            }
            if (!ws) {
                return;
            }
//            [dic setObject:result.info forKey:ws.currentIndex];
//            ws.dataDic = dic;
            ws.infoArr = result.info;
            if (ws.infoArr.count == 0) {
//                [ws setUpNoMoreNotise];
            }
            //设置page＝1，方便上拉加载时重新从第一页开始加载,
            
            ws.page = [NSString stringWithFormat:@"%ld",ws.page.integerValue +1];
//            dispatch_sync(dispatch_get, <#^(void)block#>)
            [ws.currentTabV.header endRefreshing];

            [ws.currentTabV reloadData];
        }
        KDLog(@"%@", result.info);
    } failure:^(NSError *error) {
        [ws.currentTabV.header endRefreshing];
        KDLog(@"%@",error);
        UIAlertView *messageView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"数据请求失败，请检查网络" delegate:ws cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [messageView show];
    }];
}
- (void)loadMoreDetailData{
    [self requestMethod];
    KDGetMonitorListParam *param = [self requestMethod];
    WS(ws);
    [KDMonitorRequestTool getMonitorListWithParam:param WithMainType:self.mainType success:^(KDMKeywordMonitorResult *responseObejct) {
        KDMKeywordMonitorResult *result = responseObejct;
        if ([result.status isEqualToString:@"notlogin"]) {//如果被别人强制登陆了
            //写提示“该账号已在别处登录”
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"该账号已在别处登录" message:@"请重新登录" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alertView show];
            [ws.currentTabV.header endRefreshing];
            
        }else{//正常情况下，就加载数据
            if (responseObejct.count <= ws.infoArr.count) {
                [ws.currentTabV.footer endRefreshing];
                return ;
            }
            NSMutableArray *arr = [NSMutableArray arrayWithArray:ws.infoArr];
            [arr addObjectsFromArray: result.info];
            ws.infoArr = arr;
            [ws.currentTabV reloadData];
            [ws.currentTabV.footer endRefreshing];
            if (responseObejct.count <= ws.infoArr.count) {
                [ws.currentTabV.footer endRefreshing];
            }
            //设置page++,
            ws.page = [NSString stringWithFormat:@"%ld",ws.page.integerValue +1];
            [ws.currentTabV reloadData];
            [ws.currentTabV.footer endRefreshing];
            //            KDLog(@"%@", result.info);
        }
    } failure:^(NSError *error) {
        [ws.currentTabV.footer endRefreshing];
        KDLog(@"%@",error);
        UIAlertView *messageView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"数据请求失败，请检查网络" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [messageView show];
    }];
}
#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.infoArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    KDMListCell *cell = [KDMListCell cellWithTableView:tableView andVersion:self.version];
    //    KDLog(@"waimian%d", indexPath.row);
    cell.delegate = self;
    if (tableView == self.currentTabV)
    {
        cell.delegate = self;
        if (self.infoArr.count != 0)
        {
            cell.model = self.infoArr[indexPath.row];
        }
        return cell;
    }else{
        return cell;
    }
}
/**
 *  cell被点击了
 */
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.currentTabV) {
        if (self.infoArr.count == 0) {
            return;
        }
        KDMListCell *cell = (KDMListCell *)[tableView cellForRowAtIndexPath:indexPath];
        cell.highlight = YES;
        NSMutableArray *arr = [NSMutableArray arrayWithArray:self.infoArr];
        [arr replaceObjectAtIndex:indexPath.row withObject:cell.model];
        self.infoArr = arr;
        KDMListCellBaseModel *model = self.infoArr[indexPath.row];
        GBSingleWebViewController *singleCtrl = [[GBSingleWebViewController alloc]init];
        singleCtrl.docid = model.docId;
        singleCtrl.titleee = model.title;
        singleCtrl.isCollect = model.isSave;
        singleCtrl.keyword = model.keywords;
        singleCtrl.whichPage = [NSString stringWithFormat:@"%ld",(long)indexPath.row] ;
        singleCtrl.url = model.url;
        singleCtrl.comeFrom = @"4";
        singleCtrl.report = model.isReport;
        singleCtrl.ori_content = model.content;
        singleCtrl.st = model.date;
        singleCtrl.ori_author = model.author;
        singleCtrl.ori_webname = model.source;
        
        self.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:singleCtrl animated:YES];
        self.hidesBottomBarWhenPushed = NO;
        
    }
}



#pragma mark - KDMListCellDelegate
/**
 *  上报按钮被点击了
 */
- (void)KDMListCell:(KDMListCell *)cell reportBtnClick:(UIButton *)reportBtn{
    KDMListCellBaseModel *model = cell.model;
    KDReportController *reportCtrl = [[KDReportController alloc]init];
    KDPatrolgetReportParam *param = [[KDPatrolgetReportParam alloc]init];
    param.ori_url = model.url;
    param.ori_title = model.title;
    param.ori_content = model.content;
    param.st = model.date;
    param.doc_id = model.docId;
    if (model.author.length == 0) {
        param.ori_author = @"";
    }else{
        param.ori_author = model.author;
    }
    param.ori_webname = model.source;
    reportCtrl.param = param;
    reportCtrl.type = 0;
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:reportCtrl animated:YES];
    self.hidesBottomBarWhenPushed = NO;
}
/**
 *  相关按钮被点击了
 */
- (void)KDMListCell:(KDMListCell *)cell relationBtnClick:(UIButton *)relationBtn{
    KDMListCellBaseModel *model = cell.model;
    KDMRelationController *relation = [[KDMRelationController alloc]init];
    KDGetMonitorListParam *param = [[KDGetMonitorListParam alloc]init];
    param.topicId = model.topicId;
    relation.param = param;
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:relation animated:YES];
    self.hidesBottomBarWhenPushed = NO;
}

- (void)KDMListCell:(KDMListCell *)cell collectBtnClick:(UIButton *)collectBtn{
    NSIndexPath *ip = [self.currentTabV indexPathForCell:cell];
    NSMutableArray *arr = [NSMutableArray arrayWithArray:self.infoArr];
    [arr replaceObjectAtIndex:ip.row withObject:cell.model];
    self.infoArr = arr;
}
#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if ([alertView.title isEqualToString:@"该账号已在别处登录"]) {
        switch (buttonIndex) {
            case 0:
                [self presentViewController:[[KDNewfeatureController alloc]init] animated:YES completion:nil];
                break;
            default:
                break;
        }
    }
    
}
#pragma mark - 通知接收区


@end
